package net.qa.demo.rabbitmq;

import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.jms.admin.RMQDestination;

public class OrderlyConsumer extends ConnectionFactoryTest {
	private static final Logger log = LoggerFactory.getLogger(OrderlyConsumer.class);
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ConnectionFactoryTest.setUpBeforeClass();
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		ConnectionFactoryTest.tearDownAfterClass();
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() throws Exception {
		
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		RMQDestination topic = new RMQDestination();
		topic.setAmqp(true);
		topic.setAmqpQueueName("TestQueue");
		topic.setDestinationName("TestQueue");
		
		MessageConsumer consumer = session.createConsumer(topic);
		
		consumer.setMessageListener(new MessageListener() {
			
			@Override
			public void onMessage(Message message) {
				try {
					TextMessage textMessage = (TextMessage) message;
					String text = textMessage.getText();
					log.info("JMS message received: {}", text);
				} catch (Throwable t) {  //如果此方法抛出异常，将无法收到后续消息 
					t.printStackTrace();
				}
			}
		});
		
		connection.start();
        
        log.info("JMS message listener");
		
		while (true) {
			Thread.sleep(10000);
		}
		
	}

}
